﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using thousandclear.Data;
using thousandClear.Entity;
using thousandClear.Util.Caching;
using thousandClear.Util.Setting;

namespace thousandClear.Areas.Shop.Controllers
{
    public class BaseController : Controller
    {
        private AppSetting _setting = null;

        public BaseController()
        {
            _setting = new AppSetting();
        }
        public void ProcessRequest(HttpContext context)
        {

            var appid = "wxed78d8fdb0030e29";
            var secret = "c7970dc91677b6322375fab5a8dda178";

            var code = context.Request.QueryString["Code"];
            if (string.IsNullOrEmpty(code))
            {
                var url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri=http%3a%2f%2fwx.alinq.org%2fTest%2fUserAuth.ashx&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect", appid);
                context.Response.Redirect(url);
            }
            else
            {
                var client = new System.Net.WebClient();
                client.Encoding = System.Text.Encoding.UTF8;

                var url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appid, secret, code);
                var data = client.DownloadString(url);

                var serializer = new JavaScriptSerializer();
                var obj = serializer.Deserialize<Dictionary<string, string>>(data);
                string accessToken;
                if (!obj.TryGetValue("access_token", out accessToken))
                    return;

                var opentid = obj["openid"];
                url = string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN", accessToken, opentid);
                data = client.DownloadString(url);
                var userInfo = serializer.Deserialize<Dictionary<string, object>>(data);
                foreach (var key in userInfo.Keys)
                {
                    context.Response.Write(string.Format("{0}: {1}", key, userInfo[key]) + "<br/>");
                }
            }
        }
        public OpenId GetOpenId(string code)
        {
            var client = new RestClient("https://api.weixin.qq.com/sns/oauth2");
            var request = new RestRequest("access_token?appid={appid}&secret={appsecret}&code={code}&grant_type=authorization_code", Method.GET);
            request.AddUrlSegment("appid", _setting.WeiXinAppId);
            request.AddUrlSegment("appsecret", _setting.WeiXinAppSecret);
            request.AddUrlSegment("code", code);

            //UtilNS.Util.WriteLog("GetUserInfo:accessToken:" + accessToken);
            var response = client.Execute(request);
            var data = JsonConvert.DeserializeObject<OpenId>(response.Content);

            return data;
        }

        public UserInfo GetUserInfo(string openId, string accessToken)
        {

            //var client = new RestClient("https://api.weixin.qq.com/cgi-bin/user");
            //var client = new RestClient("https://api.weixin.qq.com/sns/user");

            var request = new RestRequest("info?access_token={accessToken}&openid={openid}&lang=zh_CN", Method.GET);
            request.AddUrlSegment("openid", openId);
            request.AddUrlSegment("accessToken", accessToken);


            string sURL = string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN", accessToken, openId);
            var client = new RestClient(sURL);

            UtilNS.Util.WriteLog("GetUserInfo:openid:" + openId);
            UtilNS.Util.WriteLog("GetUserInfo:accessToken:" + accessToken);

            var response = client.Execute(request);

            var data = JsonConvert.DeserializeObject<UserInfo>(response.Content);
            UtilNS.Util.WriteLog("response.Content::" + response.Content);
            return data;
        }

        public string GetAccessToken(qianjingEntities dbContext)
        {
            string access_token = string.Empty;

            var metaData = dbContext.D_metaData.FirstOrDefault(a => a.Code == "app_access_token");

            if (metaData != null)
                access_token = metaData.Value;

            return access_token;
        }

        public ConsumerEntity GetConsumerInfo(qianjingEntities dbContext, string openId)
        {
            ConsumerEntity entiry = null;

            var record = dbContext.O_Customer.FirstOrDefault(a => a.ocOpenid == openId);

            if (record != null)
            {
                entiry = new ConsumerEntity();
                entiry.Id = record.OCID;
                entiry.Name = record.ocNicName;
                entiry.RegTime = record.CreatedDate;
            }

            return entiry;
        }

        public WechatCacheData GetCacheData(string openid)
        {
            if (!CacheProvider.Exist(openid))
                return null;

            WechatCacheData cache = (WechatCacheData)CacheProvider.Get(openid);

            return cache;
        }

        public void SetCacheData(string openid, WechatCacheData data)
        {
            CacheProvider.Set(openid, data, 24 * 60);
        }

        public bool CheckLogin(string openid, string gotourl)
        {
            var cache = GetCacheData(openid);

            if (cache == null || !cache.LoginStatus)
            {
                SetCacheData(openid, new WechatCacheData
                {
                    LoginStatus = false,
                    GotoUrl = gotourl,
                });

                return false;
            }

            return true;
        }

        public bool CheckRegister(string openid, string gotourl)
        {
            bool exists = false;

            using (qianjingEntities db = new qianjingEntities())
            {
                exists = db.O_Customer.Any(a => a.ocOpenid == openid);
            }

            if (!exists)
            {
                SetCacheData(openid, new WechatCacheData
                {
                    LoginStatus = false,
                    GotoUrl = gotourl,
                });

                return false;
            }

            return true;
        }

        public class UserInfo
        {
            public int subscribe { get; set; }
            public string openid { get; set; }
            public string nickname { get; set; }
            public int sex { get; set; }
            public string language { get; set; }
            public string city { get; set; }
            public string province { get; set; }
            public string country { get; set; }
            public string headimgurl { get; set; }
        }

        public class OpenId
        {
            public string access_token { get; set; }
            public int expires_in { get; set; }
            public string refresh_token { get; set; }
            public string openid { get; set; }
            public string scope { get; set; }
        }
        /// <summary>
        /// 新增模板至后台
        /// </summary>
        /// <param name="token">AccessToken</param>
        /// <param name="shortID">模板库中模板的编号，有“TM**”和“OPENTMTM**”等形式</param>
        public void AddModel(string token, string shortID)
        {
            try
            {
                string URL = "https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token=" + token;
                JObject input = new JObject();
                input["template_id_short"] = shortID;
                Dictionary<string, string> param = new Dictionary<string, string>();
                string requestJSON = JsonConvert.SerializeObject(param);
                param.Add("", requestJSON);
                HttpWebResponse resp = Util.Util.CreatePostHttpResponse(URL, param, 3600, null, Encoding.UTF8, null);
                if (resp.StatusCode == HttpStatusCode.OK)
                {
                    Stream resStream = resp.GetResponseStream();
                    StreamReader sr = new StreamReader(resStream);
                    string responseJSON = sr.ReadToEnd();
                    Util.Util.WriteLog("add message model success");
                    Util.Util.WriteLog("content: " + responseJSON);
                }
            }
            catch (Exception ex)
            {
                Util.Util.WriteLog("add message model Exception");
                Util.Util.WriteLog("Error: " + ex.Message);
            }
        }
        /// <summary>
        /// 获取模板列表
        /// </summary>
        /// <param name="token">AccessToken</param>
        public void GetModelList(string token)
        {
            try
            {
                string URL = "https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token=" + token;
                HttpWebResponse resp = Util.Util.CreateGetHttpResponse(URL, 3600, null, null);
                if (resp.StatusCode == HttpStatusCode.OK)
                {
                    Stream s = resp.GetResponseStream();
                    StreamReader sr = new StreamReader(s);
                    string content = sr.ReadToEnd();
                    Util.Util.WriteLog("GetModelList success");
                    Util.Util.WriteLog("content: " + content);
                }
            }
            catch (Exception ex)
            {
                Util.Util.WriteLog("GetModelList Exception");
                Util.Util.WriteLog("Error: " + ex.Message);
            }
        }
        /// <summary>
        /// 模板消息推送_评价 
        /// </summary>
        /// <param name="openid">客户ID</param>
        /// <param name="token">access token</param>
        /// <param name="serviceContent">服务内容</param>
        /// <param name="dailyRemain">日常剩余</param>
        /// <param name="specReamin">专项剩余</param>
        /// <param name="serverInfo">服务管家</param>
        /// <param name="url">打赏连接</param>
        public void SendMessage_Comment(string openid, string token, string serviceContent, int dailyRemain, int specReamin,
            string serverInfo, string url)
        {
            try
            {
                string URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token;
                JObject input = new JObject();
                input["touser"] = openid;
                input["template_id"] = "itCTZAuHfEhF32TsxpPvp9QwaUymbzK7b6h1cf8-eD4";//消息模板ID
                input["url"] = url;
                JObject content = new JObject();

                JObject p1 = new JObject();
                p1["value"] = "服务完成通知";
                p1["color"] = "#173177";
                content["first"] = p1;
                JObject p2 = new JObject();
                p2["value"] = serviceContent;
                p2["color"] = "#173177";
                content["keyword1"] = p2;
                JObject p3 = new JObject();
                p3["value"] = serverInfo;
                p3["color"] = "#173177";
                content["keyword2"] = p3;
                JObject p4 = new JObject();
                p4["value"] = "日常剩余：" + dailyRemain + "次\n专项剩余：" + specReamin + "次\n感谢您的使用，点击可以评价打赏哦！";
                p4["color"] = "#173177";
                content["remark"] = p4;

                input["data"] = content;
                Dictionary<string, string> param = new Dictionary<string, string>();
                param.Add("", JsonConvert.SerializeObject(input));
                Util.Util.WriteLog("SendMessage_Comment content: " + JsonConvert.SerializeObject(input));
                HttpWebResponse resp = Util.Util.CreatePostHttpResponse(URL, param, 3600, null, Encoding.UTF8, null);
                if (resp.StatusCode == HttpStatusCode.OK)
                {
                    Stream resStream = resp.GetResponseStream();
                    StreamReader sr = new StreamReader(resStream);
                    string responseJSON = sr.ReadToEnd();
                    Util.Util.WriteLog("add message model success");
                    Util.Util.WriteLog("content: " + responseJSON);
                }
            }
            catch (Exception ex)
            {
                Util.Util.WriteLog("send comment message Error");
                Util.Util.WriteLog("Error: " + ex.Message);
            }
        }
        /// <summary>
        /// 获取管家信息
        /// </summary>
        /// <param name="aunts"></param>
        /// <returns></returns>
        public string getAuntInfo(string aunts)
        {
            string info = "";
            try
            {
                using (var db = new qianjingEntities())
                {
                    if (aunts == "")
                    {
                        throw new Exception("aunt not found");
                    }
                    string[] _aunts = aunts.Split(',');
                    for (int i = 0; i < _aunts.Length; i++)
                    {
                        string auntid = _aunts[i];
                        string name = db.O_Aunt.Where(a => a.OATID.ToString() == auntid).FirstOrDefault().oatName;
                        string tel = db.O_Aunt.Where(a => a.OATID.ToString() == auntid).FirstOrDefault().oatPhone;
                        if (!string.IsNullOrEmpty(name))
                        {
                            info += " " + name;
                            if (!string.IsNullOrEmpty(tel))
                            {
                                info += "(" + tel + ")";
                            }
                        }

                    }
                }

            }
            catch (Exception ex)
            {
                Util.Util.WriteLog("getAuntInfo Error:input " + aunts);
                Util.Util.WriteLog("Error: " + ex.Message);
            }

            return info;
        }
    }
}